package top.jfunc.network.controller;

import org.slf4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import top.jfunc.common.utils.IoUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author xiongshiyan at 2019/5/7 , contact me with email yanshixiong@126.com or phone 15208384257
 */
public abstract class BaseController {
    public void printQueryString(Logger logger , HttpServletRequest httpServletRequest) {
        logger.info("----------------------queryString-------------------------");
        String queryString = httpServletRequest.getQueryString();
        logger.info(queryString);
    }

    public void printParams(Logger logger , HttpServletRequest httpServletRequest) {
        logger.info("----------------------parameterMap-------------------------");
        Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
        parameterMap.forEach((k ,v)->{
            logger.info(k + "----" + v[0]);
        });
    }

    public void printHeaders(Logger logger , HttpServletRequest httpServletRequest) {
        logger.info("----------------------headers-------------------------");
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            logger.info(name + "-----------" + httpServletRequest.getHeader(name));
        }
    }
    public void printBody(Logger logger , String body) {
        logger.info("----------------------body-------------------------");
        logger.info(body);
    }
    public void printMultiPart(Logger logger , MultipartFile multipartFile) throws IOException{
        logger.info("----------------------body-------------------------");
        logger.info("name:" + multipartFile.getName());
        logger.info(multipartFile.getOriginalFilename());
        logger.info(multipartFile.getContentType());
        File dest = new File(multipartFile.getOriginalFilename());
        logger.info(dest.getAbsolutePath());
        logger.info("size : " + multipartFile.getSize());
        //multipartFile.transferTo(dest);
        IoUtil.copy2File(multipartFile.getInputStream() , dest);
        IoUtil.close(multipartFile.getInputStream());
    }
}
